require('./mongoose')
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

/**
  name: 业务实例名字
  desc: 描述
  schemadef: 所属模型
  attrs： 属性值
  relations: 关联关系（引用‘关联实例’文档）
  created: 创建时间
  updated: 最后一次更新时间
  versions: 版本履历（TODO：是否能支撑版本变更业务）
*/

var AttrSchema = Schema({
  _id: false,
  key: String,
  value: Schema.Types.Mixed
});


var bizinstSchema = Schema({
  name: { type: String, required: true },
  desc: String,
  code: { type: String, unique: true, required: true },
  bizdef: { type: Schema.Types.ObjectId, ref: 'Bizdef', required: true },
  instances: [{type: Schema.Types.ObjectId, ref: 'Instance'}],
  attrs: [AttrSchema],
  relations: [{ type: Schema.Types.ObjectId, ref: 'Bizrelainst' }],
  created: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
  versions: []
}, { strict: false })

bizinstSchema.statics = {
  page: function (query, page, limit, callback) {
    if (page === undefined) page = 0
    if (limit === undefined) limit = 20
    Bizinst.count(query).then(total => {
      Bizinst
        .find(query, { versions: 0 })
        .skip((page) * limit)
        .limit(limit * 1)
        .populate({ path: 'bizdef', select: '-versions' })
        .populate('relations')
        .populate('instances')
        .exec((err, docs) => {
          callback({
            pageable: {
              totalElements: total,
              numberOfElements: docs.length,
              totalPages: Math.ceil(total / limit),
              number: page,
              first: page == 0,
              last: docs.length < limit || (docs.length === limit && (page + 1) * limit >= total),
              size: limit,
              fromNumber: page * limit,
              toNumber: page * limit + docs.length
            },
            docs
          })
        })
    })
  }
};

var Bizinst = mongoose.model('Bizinst', bizinstSchema);

module.exports = Bizinst
